//
//  GxUserAccountVM.swift
//  microblog
//
//  Created by 记忆不为 on 16/9/24.
//  Copyright © 2016年 记忆不为. All rights reserved.
//

import UIKit

class GxUserAccountVM: NSObject {
    //属性
    var account: GxUserAccount?
    //沙盒路径
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! + "/userAccount.plist"
    
    var isUserLogin: Bool {
        get {
            // 有账号 返回true
            // 没有账号 返回false
            return account != nil
        }
    }
    //单例
    static let shared = GxUserAccountVM()
    fileprivate override init() {
        super.init()
        account = loadAccount()
    }

    func loadAccessToken(code: String,complete: @escaping ((Error?)-> Void)) -> Void {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 请求参数
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        GxNetworkTool.shared.request(type: .POST, URLString: urlString, parameters: parameters, progress: nil, success: { (_, responseObject) in
            let dic = responseObject as! [String : Any]
            // 转模型
            let account = GxUserAccount(dic: dic)
            // 保存到内存中
            self.account = account
            NSKeyedArchiver.archiveRootObject(account, toFile: self.path)
            complete(nil)
            }, failure: { (_, error) in
                complete(error)
        })
    }
    private func loadAccount() -> GxUserAccount? {
        // 解档, 会调用 对象的 init?(coder aDecoder: NSCoder)
        let account = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? GxUserAccount
        
        // 需要判断accessToken的有效期,只有在有效期内才返回账号
        if let acc = account {
            // 有账号,过期时间和当前时间比较
            // 2021 > 2016
            // 测试时间,自己创造测试条件
            //            acc.expiresDate = Date(timeIntervalSinceNow: -1000)
            let date = Date()
            if acc.expiresDate?.compare(date) == ComparisonResult.orderedDescending {
                // 没有过期
                return acc
            }
        }
        
        return nil
    }
    
    func loadUserInfo(completion: @escaping (Error?) -> Void) -> Void {
        let urlString = "users/show.json"
        
        // 守卫,和可选绑定相反, userAccount?.access_token 没有值就进入分支,在后面还可以使用 access_token
        // 当一次性守卫多个,只要其中一个没有值,就会进入分支里面
        guard let access_token = account?.access_token,
            let uid = account?.uid else {
                print("userAccount?.access_token 没有值,或userAccount?.uid  没有值")
                return
        }
        
        // 在后面还可以使用 access_token
        // 参数
        let prarameters = [
            "access_token": access_token,
            "uid": uid
        ]
        // 发送get请求
        GxNetworkTool.shared.request(type: .GET, URLString: urlString, parameters: prarameters, progress: nil, success: { (_, responseObject) in
            //            print("获取用户信息成功了: \(responseObject)")
            // 获取到了数据,需要保存到模型中
            let dict = responseObject as! [String: Any]
            self.account?.screen_name = dict["screen_name"] as? String
            self.account?.avatar_large = dict["avatar_large"] as? String
            
            // 将账号保存到沙盒中
            NSKeyedArchiver.archiveRootObject(self.account!, toFile: self.path)
            completion(nil)
        }) { (_, error) in
            completion(error)
        }
    }
}
